package cn.wizzer.app.web.commons.ext.websocket.action.group;

import cn.wizzer.app.user.modules.models.GroupMember;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.GroupInfoService;
import cn.wizzer.app.user.modules.services.GroupMemberService;
import cn.wizzer.app.web.commons.ext.websocket.filter.TokenFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.framework.base.model.enums.BizExceptionEnum;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.util.param.Param4MapVerify;
import cn.wizzer.framework.util.param.ParamVerify;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

/**
 * 群主移除成员
 *
 * @author zl
 * @date 2020/6/5 15:25
 */
@IocBean
@NettyAction(uri = "/group/del/member", filters = {TokenFilter.class})
public class GroupDelMemberAction extends BaseNettyAction {

    @Inject
    @Reference
    private GroupInfoService groupInfoService;
    @Inject
    private NettyMsgUtil nettyMsgUtil;
    @Inject
    @Reference
    private GroupMemberService groupMemberService;

    @Override
    public Result action(Channel income,
                         @Param4MapVerify(fields = {@ParamVerify(name = "groupId", required = true),
                                 @ParamVerify(name = "userId", required = true)}) JSONObject params) {
        ChatUserVO self = NettyCache.globalGet(params.get("appid"));
        String groupId = params.getString("groupId");
        String userId = params.getString("userId");
        if (self.getId().equals(userId)) {
            Result.breakWith(BizExceptionEnum.REMOVE_FAIL_CAN_NOT_REMOVE_SELF);
        }

        // 查询当前操作用户的身份
        GroupMember member = groupMemberService.fetch(Cnd.where("groupId", "=", groupId).and("userId", "=", self.getId()));
        // 用户不能移除群成员
        if (member.getManager() == 0) {
            Result.breakWith(BizExceptionEnum.REMOVE_FAIL_NOT_OWNER_OR_GROUP_NOT_EXIST);
        }

        // 判断要移除的群成员用户是否存在
        GroupMember groupMember = groupMemberService.fetch(Cnd.where("groupId", "=", groupId).and("userId", "=", userId).and("delFlag", "=", 0));
        if (groupMember == null) {
            Result.breakWith(BizExceptionEnum.USER_NOT_EXIST);
        }
        // 管理员不能移除群主
        if (member.getManager() == 1 && groupMember.getManager() == 2) {
            Result.breakWith(BizExceptionEnum.PERMISSION_DENIED);
        }

        //移除群成员
        groupMemberService.delMember(userId, groupId);
        return Result.success();
    }
}
